package com.koal.util;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

@Component
public class JwtTokenUtil {

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "createdTime";
    @Value("${jwt.secret}")
    public String secret;
    @Value("${jwt.expiration}")
    public Long expiration;

    /**
     * 生成jwt令牌
     * @param userDetails
     * @return
     */
    public String generateToken(UserDetails userDetails) {
        HashMap<String,Object> map = new HashMap();
        map.put(CLAIM_KEY_USERNAME,userDetails.getUsername());
        map.put(CLAIM_KEY_CREATED,new Date());
        return Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }

    /**
     * 解析Token，返回jwt中的负载
     * @param token
     * @return
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
           claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                 .getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;
    }

    /**
     * 刷新令牌
     * @param token
     * @return
     */
    public String refreshToken(String token,UserDetails userDetails) {
        if (! checkToken(token,userDetails)) {
            System.out.println("令牌无效");
        }
        return generateToken(userDetails);

    }

    /**
     * 检查令牌是否有效
     * @param token
     * @return
     */
    public boolean checkToken(String token,UserDetails userDetails) {
        Claims claims = getClaimsFromToken(token);
        if (claims == null) {
            System.out.println("令牌无效");
            return false;
        }
        if ( ! claims.getSubject().equals(userDetails.getUsername())) {
            System.out.println("令牌无效");
            return false;
        }
        return true;
    }

}
